<?php

namespace App\Controller\Backend;

use App\Entity\AdminUserGroup;
use App\Entity\Feedback;
use App\Entity\Page;
use App\Entity\PageCategory;
use App\Entity\PageComment;
use App\Service\UploadFileService;
use App\Utils\Traits\ControllerTrait;
use App\Utils\Traits\JsonTrait;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class DefaultController extends AbstractController {
    use JsonTrait, ControllerTrait;

    /**
     * 管理模块
     * @param $sonata_admin
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function AdminModule ($sonata_admin) {
        $admin_user = $this->getUser();
        if (!is_object($admin_user)) {
            throw new AccessDeniedException('未登录，无权限访问');
        }

        $admin_modules = [];
        $admin_user_group = $this->getDoctrine()->getRepository(AdminUserGroup::class)->find($admin_user->getAdminUserGroupId());
        if (is_object($admin_user_group)) {
            // 获取可访问的模块
            $admin_modules = $this->getDoctrine()->getRepository(AdminUserGroup::class)->getAdminModuleByAdminUserGroup($admin_user_group);
        }

        return $this->render('backend/default/admin_module.html.twig', [
            'admin_modules' => $admin_modules,
            'sonata_admin'  => explode('|', $sonata_admin),
        ]);
    }

    /**
     * 用户信息区块
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function AdminUserInfo () {
        return $this->render('backend/default/admin_user_info.html.twig', []);
    }

    /**
     * 留言通知
     * @param PaginatorInterface $paginator
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function message (PaginatorInterface $paginator) {
        $dql = "SELECT p from App\Entity\Feedback as p where p.status = 0 order by p.id DESC";
        $query = $this->getDoctrine()->getManager()->createQuery($dql);
        $pagination = $paginator->paginate($query, 1, 5);
        return $this->render('backend/default/message.html.twig', [
            'pagination' => $pagination,
        ]);
    }

    /**
     * 消息通知
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function notification () {
        $page_comment_total = $this->getDoctrine()->getRepository(PageComment::class)->getPendingTotal();
        $total = 0;
        if ($page_comment_total > 0) {
            $total++;
        }
        return $this->render('backend/default/notification.html.twig', [
            'page_comment_total' => $page_comment_total,
            'total' => $total,
        ]);
    }

    /**
     * 控制面板(经典)
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function DashboardTypeClassics () {
        $admin_user = $this->getUser();
        if (!is_object($admin_user)) {
            throw new AccessDeniedException('未登录，无权限访问');
        }

        $admin_modules = [];
        $admin_user_group = $this->getDoctrine()->getRepository(AdminUserGroup::class)->find($admin_user->getAdminUserGroupId());
        if (is_object($admin_user_group)) {
            // 获取可访问的模块
            $admin_modules = $this->getDoctrine()->getRepository(AdminUserGroup::class)->getAdminModuleByAdminUserGroup($admin_user_group);
        }

        return $this->render('backend/default/dashboard_type_classics.html.twig', [
            'admin_modules' => $admin_modules,
        ]);
    }

    /**
     * 控制面板(工作台)
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function DashboardTypeWorkbench () {
        $admin_user = $this->getUser();
        if (!is_object($admin_user)) {
            throw new AccessDeniedException('未登录，无权限访问');
        }

        $page_total = $this->getDoctrine()->getRepository(Page::class)->getPageTotal();
        $page_comment_total = $this->getDoctrine()->getRepository(PageComment::class)->getCommentTotal();
        $page_view_total = $this->getDoctrine()->getRepository(Page::class)->getPageViewTotal();
        $_page_category_scale = $this->getDoctrine()->getRepository(PageCategory::class)->getTopCategory(true);
        $page_hots = $this->getDoctrine()->getRepository(Page::class)->getHotPage(6, true);
        $feedback = $this->getDoctrine()->getRepository(Feedback::class)->getNewFeedback();
        $page_comment = $this->getDoctrine()->getRepository(PageComment::class)->getNewComment(3, true);

        // 类别排序
        $scale = $category_scale = $page_category_scale = [];
        foreach ($_page_category_scale as $item) {
            $scale[$item['id']] = $item['num'];
            $category_scale[$item['id']] = $item;
        }
        arsort($scale);
        foreach ($scale as $id => $num) {
            array_push($page_category_scale, $category_scale[$id]);
        }

        return $this->render('backend/default/dashboard_type_workbench.html.twig', [
            'page_total'                 => $page_total,
            'page_comment_total'         => $page_comment_total,
            'page_view_total'            => $page_view_total,
            'page_category_scale'        => array_slice($page_category_scale, 0, 8),
            'page_category_scale_colors' => ['#f56954', '#00a65a', '#f39c12', '#00c0ef', '#3c8dbc', '#d2d6de', '#f39c12', '#00c0ef'],
            'page_hots'                  => $page_hots,
            'feedback'                   => $feedback,
            'page_comment'               => $page_comment,
        ]);
    }

    /**
     * 图片上传
     * @Route("/admin/default/image_update/{path}", name="admin_default_image_upload")
     * @param ContainerInterface $container
     * @param Request $request
     * @param $path
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function imageUploadAction (ContainerInterface $container, Request $request, $path) {
        if ($this->isAppModeDemo()) {
            return $this->jsonFailure('Demo模式下禁止图片上传');
        }

        if ($request->getMethod() != 'POST') {
            return $this->jsonFailure('请求错误');
        }

        $absolute_save_path = $this->getParameter('kernel.image_upload.absolute.dir').$path.DIRECTORY_SEPARATOR;
        $relative_save_path = $this->getParameter('kernel.image_upload.relative.dir').$path.DIRECTORY_SEPARATOR;
        $allow_type = ['jpg', 'png', 'jpeg'];
        $max_size = 1 * 1024 * 1024;
        $file = $_FILES['file_data'];
        $uploadFileService = $container->get('app.service.upload_file');
        $upload_result_obj = $uploadFileService->upload($absolute_save_path, $relative_save_path, $allow_type, $max_size, $file);
        if ($upload_result_obj->type == UploadFileService::MESSAGE_TYPE_SUCCESS) {
            return $this->jsonSuccess([
                'url' => $upload_result_obj->relative_file_path,
            ]);
        } else {
            return $this->jsonFailure($upload_result_obj->message);
        }
    }

}
